<template>
  <el-card>
    <el-input v-model="roleName" disabled />
    <el-tree
      :data="permissionList"
      :props="{
        children: 'children',
        label: 'name',
      }"
      ref="treeRef"
      node-key="id"
      show-checkbox
      default-expand-all
    />
    <el-button type="primary" @click="assignRolePermission">确定</el-button>
    <el-button @click="cancel">取消</el-button>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "RoleAuth",
};
</script>

<script lang="ts" setup>
import type { PermissionList } from "@/api/acl/models/permissionModel";
import {
  getRolePermissionListApi,
  assignRolePermissionApi,
} from "@/api/acl/permission";
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";

const treeRef = ref();

const route = useRoute();
const router = useRouter();
const roleName = route.query.roleName as string;

const permissionList = ref<PermissionList>([]);

onMounted(async () => {
  const res = await getRolePermissionListApi(route.query.id as string);
  permissionList.value = res.children;
  const ids = getSelectIds(res.children);
  treeRef.value.setCheckedKeys(ids);
});

const getSelectIds = (permissionList: PermissionList) => {
  let ids: string[] = [];
  permissionList.forEach((permission) => {
    if (permission.children && permission.children.length) {
      const childrenIds = getSelectIds(permission.children);
      ids = [...ids, ...childrenIds];
    } else {
      if (permission.select) {
        ids.push(permission.id);
      }
    }
  });
  return ids;
};

const cancel = () => {
  router.push({
    name: "Role",
  });
};

const assignRolePermission = async () => {
  // 获取所有选中的key
  const checkedKeys = treeRef.value.getCheckedKeys();
  // 获取所有半选的key
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  await assignRolePermissionApi(route.query.id as string, [
    ...checkedKeys,
    ...halfCheckedKeys,
  ]);

  ElMessage.success("分配角色权限成功");
  cancel()
};
</script>

<style scoped></style>
